<<<<<<< HEAD:数据处理 version6.py
# -*- coding = utf-8 -*-
# @Time : 2022/4/13 18:58
# @Author : Gan Yuyang
# @File : 数据处理 version2.py
# @Software: PyCharm

import numpy as np
import docx
from docx.oxml.ns import qn
from docx.shared import Pt, RGBColor
import os
import time
import pyautogui as pag
# import sympy as sy
from sympy import pi
from sympy import sqrt, latex, simplify, sympify, expand, factor, symbols, log, diff


def get_eff_len(num):
    num = str(num)
    num_dict = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    list1 = list(num)
    eff_len = 0
    count_start = 0

    for number in list1:
        if number in num_dict and number != '0':
            count_start = 1
        if count_start != 0 and number in num_dict:
            eff_len += 1

    return eff_len


def eff_num(num, eff_len):
    num_dict = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    num = float(num)
    num = str(num)
    exp = 0

    # 长度不够(末尾是0防止舍去)
    if get_eff_len(num) < eff_len:
        num = list(num)
        if '.' not in num:
            num.append('.')
        while get_eff_len(num) < eff_len:
            num.append('0')
        str1 = ''.join(num)
        return str1

    while float(num) >= pow(10, eff_len):
        num = str(float(num) / 10)
        exp += 1
    if get_eff_len(num) >= eff_len:
        k = len(num) - get_eff_len(num) + eff_len - 1
        num = list(num)
        if '.' not in num:
            num.append('.')
        num.append('0')
        final = int(num[k + 1])

        if num[k] == '.':
            k -= 1
        if final <= 4 or final == 5 and int(num[k]) % 2 == 0:
            pass
        if final >= 6 or final == 5 and int(num[k]) % 2 != 0:
            i = k
            while i >= 0:
                if num[i] == '.':
                    i -= 1
                    continue
                num[i] = str(int(num[i]) + 1)
                if num[i] in num_dict and int(num[i]) < 10:
                    break
                if num[i] == '10' and i != 0:
                    num[i] = '0'
                i -= 1
        while get_eff_len(num) > eff_len:
            num.pop()
        if num[-1] == '.':
            num.pop()
        num = ''.join(num)
        if float(num) >= pow(10, eff_len):
            num = eff_num(num, eff_len)
        if exp:
            num += '*10^' + str(exp)
        return num


def eff_first(num):
    num = str(num)
    num = list(num)
    i = 0
    while num[i] == '0' or num[i] == '.':
        i += 1
    return i, num[i]


def er_fendu(num):
    num = str(num)
    num = list(num)
    i = 0
    k = 0
    if num[0] != '0':
        num.append('.')
        while num[i] != '.':
            i += 1
        return num[0], i - 1
    if num[0] == '0':
        while num[i] == '0' or num[i] == '.':
            if i == len(num) - 1:
                return '0', len(num) - 1
            i += 1
            k -= 1
        return num[i], k + 1


def calcu_eff(num, fendu):
    # 首位肯定是0
    num = str(num)
    num = list(num)
    first1, f1 = er_fendu(''.join(num))
    return f1 - fendu + 1


def deci_len(num):
    num = str(num)
    if '.' not in num:
        return 0
    else:
        return len(num) - num.index('.') - 1


def zero_deci(decilen):
    str1 = '0'
    if not decilen:
        return str1
    else:
        str1 = str1 + '.'
        while deci_len(str1) < decilen:
            str1 = str1 + '0'
        return str1


def angle2float(num):
    # 分光计只有到xx'的读数, 所以并不支持读到xx''
    num = str(num)
    """
    num has the form of xxx,xxx, '.' is replaced by ','
    """
    if ',' not in num:
        return num
    else:
        pos = num.index(',')
        len1 = len(num)
        int_part = int(num[:pos])
        float_part = float('0.' +
                           str(1 / 6 *
                               float(num[pos + 1:len1])).replace('.', ''))
        total_part = int_part + float_part
        return eff_num(total_part, 6)

    # return f_num


def float2angle(num):
    """
    num is now a float or a str
    """
    num = str(num)
    '''
    we regard angle2num a float with .
    '''
    pos = num.index('.')
    num = num + '0'
    f_1 = num[0:pos]
    f_2 = num[pos + 1:pos + 3]
    a_1 = f_1
    a_2 = int(0.6 * int(f_2))
    a_2 = str(a_2)
    print(a_2)
    return a_1 + '°' + a_2 + '\''


def operate(path, path_s='', x_bias=0, y_bias=0, confidence=0.8, click=True):
    while True:
        img = pag.locateOnScreen(path, confidence=confidence)
        if path_s != '':
            img_s = pag.locateOnScreen(path_s, confidence=0.8)
        else:
            img_s = None
        if img_s is not None:
            print('already done')
            break
        if img is not None:
            print('image finded')
            x, y = pag.center(img)
            if click:
                pag.leftClick(x + x_bias, y + y_bias)
                break
            else:
                pag.moveTo(x + x_bias, y + y_bias)
                break
        else:
            print('failed')


data_storage = []
angle_storage = []
print('这个程序会生成(或在现存的docx文档后添加)一个docx格式的文档, 包含了大物实验的数据处理和误差分析部分')
path = input('输入word的文件名(可以不存在, 会新建的), 并且包含它的路径(比如D:/Experiments/切变模量):')
if 'docx' not in path:
    path = path + '.docx'

print(path)
P = input("输入实验的置信系数0.68(default),0.90,0.95   (选择1,2,3也行):")
if P == '':
    P = '0.68'
if P == '1':
    P = '0.68'
if P == '2':
    P = '0.90'
if P == '3':
    P = '0.95'
Greek_list = [
    'alpha', 'delta', 'epsilon', 'varepsilon', 'eta', 'theta', 'vartheta',
    'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'rho', 'sigma', 'tau',
    'upsilon', 'phi', 'chi', 'psi', 'omega', 'varphi'
]
print('警告--------警告---------警告')
print('变量符号  不能是 C , O,  Q, N, I, E, S, beta, gamma, zeta, pi')
print('变量符号  不能是 C , O,  Q, N, I, E, S, beta, gamma, zeta, pi')
print('变量符号  不能是 C , O,  Q, N, I, E, S, beta, gamma, zeta, pi')
forbiden_list = [
    'C', 'O', 'Q', 'N', 'I', 'E', 'S', 'beta', 'gamma', 'zeta', 'pi'
]
time.sleep(3)
print('实在要用必须加上下标')

while True:
    name = input('输入测量量名称, 若不需要输入done:')

    if name == 'done':
        break
    remake_name = 're'
    i = 0
    while remake_name == 're':
        if i == 0:
            remake_name = input('输入测量量符号(用来计算的核心部分, 千万别错了):')
        else:
            name = input('输入测量量名称, 若不需要输入done:')
            if name == 'done':
                break
            remake_name = input('输入测量量符号(用来计算的核心部分, 千万别错了):')
        i += 1
    i = 0
    if name == 'done':
        break

    figure = remake_name
    if figure in forbiden_list:
        print('不合法的变量名, 更换名字或者添加下标')
        continue
    Gf = False
    for item in Greek_list:
        if item in figure:
            Gf = True
            break
    print('Greek_figure:', Gf)
    if Gf:
        gf = '\\'
    else:
        gf = ''
    remake_figure = 're'
    while remake_figure == 're':
        if i == 0:
            remake_figure = input('输入数据:')
        else:
            figure = input('输入测量量符号(用来计算的核心部分, 千万别错了):')
            remake_figure = input('输入数据:')
        i += 1

    remake_data = 're'

    data_list = remake_figure
    i = 0
    while remake_data == 're':
        if i == 0:
            remake_data = input('输入测量量单位, 不要打括号:')
        else:
            data_list = input('输入数据:')
            remake_data = input('输入测量量单位, 不要打括号:')
        i += 1
    data_list = data_list.split()
    var_is_angle = False
    if ',' in data_list[0]:
        var_is_angle = True
        for i in range(len(data_list)):
            # print(item)
            data_list[i] = angle2float(data_list[i])
            # print(item)
    print(data_list)
    len_data = len(data_list)
    if len_data == 2:
        print('故意找茬是吧')
        continue
    if len_data >= 3:
        enough_data = True
    else:
        enough_data = False

    remake_dw = 're'
    dw = remake_data
    i = 0
    while remake_dw == 're':
        if i == 0:
            remake_dw = input('输入分布类型   正态(default),均匀,三角   (选择1,2,3): ')
        else:
            dw = input('输入测量量单位, 不要打括号:')
            remake_dw = input('输入分布类型   正态(default),均匀,三角   (选择1,2,3): ')
        i += 1
    if not enough_data:

        print('distribute type automatically set to triangular')
        distribute_type = 3
        remake_distribute = input('输入仪器允差:')
    else:
        remake_distribute = 're'
        distribute_type = remake_dw
        i = 0
        while remake_distribute == 're':
            if i == 0:
                remake_distribute = input('输入仪器允差:')
            else:
                distribute_type = input('输入分布类型   正态,均匀,三角   (选择1,2,3): ')
                remake_distribute = input('输入仪器允差:')
        i += 1
        if distribute_type == '':
            distribute_type = 1
    distribute_type = int(distribute_type)

    remake_delta = 're'
    if ',' in remake_distribute:
        remake_distribute = angle2float(remake_distribute)
    delta = float(remake_distribute)
    i = 0
    # delta = float(input('输入仪器允差:'))
    # print('下方粘贴数据(手动输入以空格分割), 回车(不支持多行输入):')
    while remake_delta == 're':
        if i == 0:
            remake_delta = input('re?不re敲回车')
        else:
            delta = float(input('输入仪器允差:'))
            remake_delta = input('re?不re敲回车')
        i += 1
    eff_len = get_eff_len(data_list[0])
    for i in range(len_data):
        data_list[i] = float(data_list[i])

    if enough_data:
        u_a = np.std(data_list) / np.sqrt(len_data - 1)
    else:
        u_a = 0.0

    T_A = {
        '1': [-1, 0, -1, 1.32, 1.2, 1.14, 1.11, 1.09, 1.08, 1.07, 1.06],
        '2': [-1, -1, -1, 2.92, 2.35, 2.13, 2.02, 1.94, 1.86, 1.83, 1.76],
        '3': [-1, -1, -1, 4.30, 3.18, 2.78, 2.57, 2.46, 2.37, 2.31, 2.26],
        '0.68': [-1, -1, -1, 1.32, 1.2, 1.14, 1.11, 1.09, 1.08, 1.07, 1.06],
        '0.90': [-1, -1, -1, 2.92, 2.35, 2.13, 2.02, 1.94, 1.86, 1.83, 1.76],
        '0.95': [-1, -1, -1, 4.30, 3.18, 2.78, 2.57, 2.46, 2.37, 2.31, 2.26]
    }

    t_A = T_A[P][len_data]

    K_P = {
        '1': [1.000, 1.183, 1.064],
        '2': [1.650, 1.559, 1.675],
        '3': [1.960, 1.645, 1.901],
        '0.68': [1.000, 1.183, 1.064],
        '0.90': [1.650, 1.559, 1.675],
        '0.95': [1.960, 1.645, 1.901]
    }
    C = [3, np.sqrt(3), np.sqrt(6)]
    c = C[distribute_type - 1]
    C_s = ['3', '\sqrt{3}', '\sqrt{6}']
    k_p = K_P[P][distribute_type - 1]

    U = np.sqrt(np.square(t_A * u_a) + np.square(k_p * delta / c))
    first = er_fendu(U)[0]
    if first == '1' or first == '2':
        U = eff_num(str(U), 2)
    else:
        U = eff_num(str(U), 1)
    ave = np.average(data_list)
    ave = str(ave)

    if enough_data:
        std = np.std(data_list) * np.sqrt(len_data) / np.sqrt(len_data - 1)
    else:
        std = 0

    ave_fendu = er_fendu(ave)
    U_fendu = er_fendu(U)
    if er_fendu(ave)[1] <= er_fendu(U)[1]:
        print('故意找茬是吧, 误差这么大')
        continue
    ave = eff_num(
        ave,
        max(
            abs(er_fendu(ave)[1] - er_fendu(U)[1]) + 1,
            get_eff_len(str(data_list[0])) + 1))

    if std:
        std = eff_num(str(std), 2)
    else:
        std = zero_deci(deci_len(ave))
    if u_a:
        first = er_fendu(u_a)[0]
        if first == '1' or first == '2':
            u_a = eff_num(str(u_a), 2)
        else:
            u_a = eff_num(str(u_a), 1)
    else:
        u_a = zero_deci(deci_len(ave))

    print('ave=', ave)
    print('std=', std)
    if enough_data:
        print('u_a=', u_a)

    print('C=', C_s[distribute_type - 1])
    if enough_data:
        print('t_A=', t_A)
    print('k_p=', k_p)
    U_r = eff_num(str(float(U) / np.average(data_list) * 100), 2)
    print('U_测=', U)
    print('U_r=', U_r + '%')
    #     现在进行变量处理
    u_figure = 'U_' + figure

    trans = ''
    if var_is_angle:
        trans = input('转换为弧度制(default), 输入N取消 (角度制只能加减):')

    if var_is_angle and not trans == 'N':
        ave_1 = float(ave) * 3.1415926 / 180
        U_1 = float(U) * 3.1415926 / 180
    else:
        ave_1 = float(ave)
        U_1 = float(U)
    globals()[figure] = symbols(figure)
    globals()[u_figure] = symbols(u_figure)
    if not var_is_angle:
        data_storage.append(
            ((globals()[figure], float(ave)), (globals()[u_figure], float(U))))
    else:
        data_storage.append(((globals()[figure], float(ave_1)),
                             (globals()[u_figure], float(U_1))))

    if var_is_angle:
        for i in range(len_data):
            data_list[i] = float2angle(data_list[i])
        ave = float2angle(ave)
        if enough_data:
            u_a = float2angle(u_a)
        std = float2angle(std)
        U = float2angle(U)
    try:
        doc = docx.Document(path)
    except Exception:
        doc = docx.Document()
    doc.styles['Normal'].font.name = u'宋体'
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    doc.styles['Normal'].font.size = Pt(10.5)
    doc.styles['Normal'].font.color.rgb = RGBColor(0, 0, 0)

    para_3 = doc.add_paragraph('')

    if enough_data:
        if dw:
            header = doc.add_paragraph(name + '{\quad}' + gf + figure + '(' +
                                       dw + ')' + ':')
        else:
            header = doc.add_paragraph(name + '{\quad}' + gf + figure + ':')

    else:
        if dw:
            header = doc.add_paragraph(name + '{\quad}' + gf + figure + '(' +
                                       dw + ')' + ':' + '{\qquad}' +
                                       str(data_list[0]))
        else:
            header = doc.add_paragraph(name + '{\quad}' + gf + figure + ':' +
                                       '{\qquad}' + str(data_list[0]))

    if enough_data:
        try:
            table = doc.add_table(rows=2,
                                  cols=len_data + 1,
                                  style='Table Grid')
        except Exception:
            table = doc.add_table(rows=2,
                                  cols=len_data + 1,
                                  style='Normal Table')

        line1 = table.rows[0].cells
        line1[0].text = '组数'
        for i in range(1, len_data + 1):
            line1[i].text = str(i)
        line2 = table.rows[1].cells
        line2[0].add_paragraph('读数 ')
        for i in range(1, len_data + 1):
            line2[i].add_paragraph(str(data_list[i - 1]))
    if enough_data:
        para_1 = doc.add_paragraph('')
    para0 = doc.add_paragraph('P=' + str(P))
    if dw:
        para1 = doc.add_paragraph('\\bar' + '{' + gf + figure + '}' + '=' +
                                  str(ave) + '' + dw)
        para2 = doc.add_paragraph('\\sigma_' + '{' + gf + figure + '}' + '=' +
                                  str(std) + ' ' + dw)
    else:
        para1 = doc.add_paragraph('\\bar' + '{' + gf + figure + '}' + '=' +
                                  str(ave))
        para2 = doc.add_paragraph('\\sigma_' + '{' + gf + figure + '}' + '=' +
                                  str(std))
    if enough_data:
        para5 = doc.add_paragraph('u_A =' + str(u_a) + ' ' + dw + '{\qquad}' +
                                  't_A=' + str(t_A))
    para4 = doc.add_paragraph('C=' + C_s[distribute_type - 1] + '{\qquad}' +
                              'k_p' + '=' + str(k_p))

    para7 = doc.add_paragraph('U_' + '{' + gf + figure + '}' + '=' + str(U) +
                              ' ' + dw + '{\qquad}' + 'U_r=' + str(U_r) + '%')
    if dw:
        para9 = doc.add_paragraph(gf + figure + '=' + '(' + ave + '\\pm ' + U +
                                  ')' + ' ' + dw)
    else:
        para9 = doc.add_paragraph(gf + figure + '=' + ave + '\\pm ' + U)

    doc.save(path)
    print(name + '      录入成功')

print(data_storage)

var_all = []
for i in range(len(data_storage)):
    var_all.extend(data_storage[i])

# 合成处理
while True:
    print('涉及角度的量, 只要不是加减法, 都要使用弧度制')
    name = input('物理量(final)名称, 输入done退出:')

    if name == 'done':
        break
    remake_name = 're'
    i = 0
    while remake_name == 're':
        if i == 0:
            remake_name = input('输入物理量符号:')
        else:
            name = input('物理量(final)名称, 输入done退出:')
            if name == 'done':
                break
            remake_name = input('输入物理量符号:')
        i += 1
    if name == 'done':
        break

    figure = remake_name

    remake_figure = 're'

    i = 0
    while remake_figure == 're':
        if i == 0:
            remake_figure = input('输入单位:')
        else:
            figure = input('输入物理量符号:')
            remake_figure = input('输入单位:')
        i += 1
    Gf = False
    for item in Greek_list:
        if item in figure:
            Gf = True
            break
    print('Greek_figure:', Gf)
    if Gf:
        gf = '\\'
    else:
        gf = ''

    # dw = input('输入单位:')
    dw = remake_figure
    remake_dw = 're'
    i = 0

    while remake_dw == 're':
        if i == 0:
            remake_dw = input('输入物理量的表达式(支持^表示次方, 还有不要少打括号!!!):')
        else:
            remake_dw = input('输入物理量的表达式(支持^表示次方, 还有不要少打括号!!!):')
            dw = input('输入单位:')
        i += 1

    str_expr = remake_dw
    remake_str = 're'
    i = 0
    while remake_str == 're':
        if i == 0:
            remake_str = input()
        else:
            str_expr = input('输入物理量的表达式(支持^表示次方, 还有不要少打括号!!!):')
            remake_str = input()

    # U_r = symbols('U_r')
    # U = symbols('U')

    str_expr.replace('^', '**')
    print(var_all)
    try:
        expr = sympify(str_expr, rational=True)
    except Exception:
        print(Exception)
        continue

    ave = float(expr.subs(var_all).evalf())
    print(ave)
    # 输出公式的LaTeX公式
    latex_expr = latex(expr, ln_notation=True)
    # print(latex_expr)
    expr1 = log(expr)
    expr2 = 0

    sig_var = []

    for item in data_storage:

        expr2 = expr2 + (diff(expr1, item[0][0]) * item[1][0])**2
        Gf_1 = False
        for elem in Greek_list:
            if elem in str(item[0][0]):
                Gf_1 = True
                break
        print('var is Greek_figure:', Gf_1)
        if Gf_1:
            gf_1 = '\\'
        else:
            gf_1 = ''

        expr3 = diff(expr1, item[0][0])
        if str(expr3)[0] == '-':
            expr3 = -1 * expr3
        if str(expr3)[0] != '0':
            expr3 = simplify(expr3)
            expr3 = expand(expr3)
            expr3 = factor(expr3)

            sig_var.append('(' + latex(expr3) + 'U_' + '{' + gf_1 +
                           str(item[0][0]) + '}' + ')' + '^' + '{' + '2' + '}')

    expr2 = sqrt(expr2)
    print(expr2)
    latex_u_in = '+'.join(sig_var)
    latex_u_in = '\\sqrt' + '{' + latex_u_in + '}'
    print(latex_u_in)

    U_r = float(expr2.subs(var_all).evalf())
    print('U_r=', U_r)
    U = ave * U_r
    ave = eff_num(ave, min(abs(er_fendu(ave)[1] - er_fendu(U)[1]) + 1, 7))

    U_r = eff_num(100 * U_r, 2) + '%'
    first = er_fendu(U)[0]
    if first == '1' or first == '2':
        U = eff_num(str(U), 2)
    else:
        U = eff_num(str(U), 1)

    doc = docx.Document(path)

    doc.add_paragraph('')
    doc.add_paragraph('')
    if dw:
        Para_1 = doc.add_paragraph(name + '{\quad}' + gf + figure + '(' + dw +
                                   ')' + ':')
        Para_0 = doc.add_paragraph('P=' + str(P))
        Para_2 = doc.add_paragraph(gf + figure + '=' + latex_expr + '=' + ave +
                                   '(' + dw + ')')
    else:
        Para_1 = doc.add_paragraph(name + '{\quad}' + gf + figure + ':')
        Para_0 = doc.add_paragraph('P=' + str(P))
        Para_2 = doc.add_paragraph(gf + figure + '=' + latex_expr + '=' + ave)
    Para_3 = doc.add_paragraph('U_r =' + '\\frac{U_{' + gf + figure + '}}{' +
                               gf + figure + '}' + '=' + latex_u_in + '=' +
                               U_r)
    if dw:
        Para_4 = doc.add_paragraph('U =' + gf + figure + '\\times' + ' ' +
                                   'U_r' + '=' + U + '(' + dw + ')')
        Para_5 = doc.add_paragraph(gf + figure + '=' + '(' + ave + '\\pm' + U +
                                   ')' + dw)
    else:
        Para_4 = doc.add_paragraph('U =' + gf + figure + '\\times' + ' ' +
                                   'U_r' + '=' + U)
        Para_5 = doc.add_paragraph(gf + figure + '=' + '(' + ave + '\\pm' + U +
                                   ')')
    doc.save(path)
    print(name + '  ' + '处理完成')
"""
最后的文件处理
"""

os.startfile(path)
operate("./user.jpg", click=False)
# 判断文件已经打开
pag.moveRel(0, 500)
time.sleep(3)

pag.hotkey('ctrl', 'end')
time.sleep(0.3)

pag.hotkey('ctrl', 'shiftright', 'shiftleft', 'home')

time.sleep(1)
pag.hotkey('alt', '=')
time.sleep(0.1)
pag.hotkey('alt', 'shift', 'p')
time.sleep(0.1)
pag.hotkey('ctrl', 'l')
time.sleep(1)
pag.hotkey('ctrl', 's')

print('finished')
=======
# -*- coding = utf-8 -*-
# @Time : 2022/4/13 18:58
# @Author : Gan Yuyang
# @File : 数据处理 version2.py
# @Software: PyCharm
"""
发现eff_num函数里一个巨大的bug, 就是发现有效数字和需要的相等时居然没有直接return
导致会出一个及其严重的问题, 比如3 放入后, 会被生成为['3','.'], '.'不能作为结尾,
(因为不能化成十进制)
"""

import numpy as np
import docx
from docx.oxml.ns import qn
from docx.shared import Pt, RGBColor
import os
import time
import pyautogui as pag
from sympy import pi
from sympy import sqrt, latex, simplify, sympify, expand, factor, symbols, log, diff


# 在eff_num里加了eval
def pure_sci2str(num):
    if type(num) == list:
        num = ''.join(num)
    num = float(num)
    num = str(num)
    if 'e' not in num:
        return num
    else:
        if 'e-' not in num:
            return float(num)
        else:
            len_1 = len(num)
            pos = num.index('e-')
            len_0 = int(num[pos + 1:len_1])
            print(len_0)
            len_0 = -1 * len_0
            z_d_0 = len_0 - 1
            str1 = '0.'
            num_1 = num[0:pos]

            num_1 = num_1.replace('.', '')
            for i in range(z_d_0):
                str1 += '0'

            str1 += num_1
            return str1


def sci2str(num):
    if type(num) is list:
        num = ''.join(num)
    num = str(num)
    num = num.replace('^', '**')
    num = eval(num)
    num = str(num)

    if 'e-' not in num:
        first = er_fendu(num)[0]
        if first == '1' or first == '2':
            str1 = eff_num(str(num), 2)
        else:
            str1 = eff_num(str(num), 1)
        return str1

    else:
        len_1 = len(num)
        pos = num.index('e-')
        len_0 = int(num[pos + 1:len_1])
        print(len_0)
        len_0 = -1 * len_0
        z_d_0 = len_0 - 1
        str1 = '0.'
        num_1 = num[0:pos]
        if eff_first(num_1)[1] == '1' or eff_first(num_1)[1] == '1':

            num_1 = eff_num(num[0:pos], 2)
        else:
            num_1 = eff_num(num[0:pos], 1)
        num_1 = num_1.replace('.', '')
        for i in range(z_d_0):
            str1 += '0'

        str1 += num_1
        return str1


def get_eff_len(num):
    if type(num) is list:
        num = ''.join(num)
    num = str(num)
    num_dict = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    list1 = list(num)
    eff_len = 0
    count_start = 0

    for number in list1:
        if number in num_dict and number != '0':
            count_start = 1
        if count_start != 0 and number in num_dict:
            eff_len += 1

    return eff_len


def eff_num(num, eff_len):
    num_dict = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    if type(num) is list:
        num = ''.join(num)
    num = str(num)
    num = num.replace('^', '**')
    num = eval(num)
    num = str(num)
    num = pure_sci2str(num)
    exp = 0
    if get_eff_len(num) == eff_len:
        return num
    # 长度不够(末尾是0防止舍去)
    if get_eff_len(num) < eff_len:
        num = list(num)
        if '.' not in num:
            num.append('.')
        while get_eff_len(num) < eff_len:
            num.append('0')
        str1 = ''.join(num)
        return str1

    while float(num) >= pow(10, eff_len):
        num = str(float(num) / 10)
        exp += 1

    if get_eff_len(num) > eff_len:
        k = len(num) - get_eff_len(num) + eff_len - 1

        num = list(num)

        if '.' not in num:
            num.append('.')

        num.append('0')
        final = int(num[k + 1])

        if num[k] == '.':
            k -= 1
        if final <= 4 or final == 5 and int(num[k]) % 2 == 0:
            pass
        if final >= 6 or final == 5 and int(num[k]) % 2 != 0:
            i = k
            while i >= 0:
                if num[i] == '.':
                    i -= 1
                    continue
                num[i] = str(int(num[i]) + 1)
                if num[i] in num_dict and int(num[i]) < 10:
                    break
                if num[i] == '10' and i != 0:
                    num[i] = '0'
                i -= 1
        while get_eff_len(num) > eff_len:
            num.pop()
        if num[-1] == '.':
            num.pop()
        num = ''.join(num)
        if float(num) >= pow(10, eff_len):
            num = eff_num(num, eff_len)
        if exp:
            num += '*10^' + str(exp)
        return num


def eff_first(num):
    if type(num) is list:
        num = ''.join(num)
    num = str(num)
    num = list(num)
    i = 0
    while num[i] == '0' or num[i] == '.':
        i += 1
    return i, num[i]


def er_fendu(num, error=1):
    if type(num) is list:
        num = ''.join(num)
    num = str(num)
    if 'e-' in num:
        num = sci2str(num)
    num = list(num)
    i = 0
    k = 0
    if num[0] != '0':
        num.append('.')

        while num[i] != '.':
            i += 1
        if error and (num[0] == '1' or num[0] == '2'):
            i -= 1
        return num[0], i - 1
    if num[0] == '0':
        while num[i] == '0' or num[i] == '.':
            if i == len(num) - 1:
                return '0', len(num) - 1
            i += 1
            k -= 1

        if num[i] == '1' or num[i] == '2':
            if error:
                return num[i], k
            else:
                return num[i], k + 1
        else:

            return num[i], k + 1


def calcu_eff(num, fendu):
    # 首位肯定是0
    num = str(num)
    if 'e-' in num:
        num = sci2str(num)
    num = list(num)
    first1, f1 = er_fendu(''.join(num))
    return f1 - fendu + 1


def deci_len(num):
    num = str(num)
    if 'e-' in num:
        num = sci2str(num)
    if '.' not in num:
        return 0
    else:
        return len(num) - num.index('.') - 1


def zero_deci(decilen):
    str1 = '0'
    if not decilen:
        return str1
    else:
        str1 = str1 + '.'
        while deci_len(str1) < decilen:
            str1 = str1 + '0'
        return str1


def angle2float(num):
    # 分光计只有到xx'的读数, 所以并不支持读到xx''
    num = str(num)

    """
    num has the form of xxx,xxx, '.' is replaced by ','
    """
    if ',' not in num:
        return num
    else:
        pos = num.index(',')
        len1 = len(num)
        int_part = int(num[:pos])
        float_part = float('0.' + str(1 / 6 * float(num[pos + 1:len1])).replace('.', ''))
        total_part = int_part + float_part
        return eff_num(total_part, 6)

    # return f_num


def float2angle(num):
    """
    num is now a float or a str
    """
    num = str(num)
    '''
    we regard angle2num a float with .
    '''
    pos = num.index('.')
    num = num + '0'
    f_1 = num[0:pos]
    f_2 = num[pos + 1: pos + 3]
    a_1 = f_1
    a_2 = int(0.6 * int(f_2))
    a_2 = str(a_2)
    print(a_2)
    return a_1 + '°' + a_2 + '\''


def operate(path, path_s='', x_bias=0, y_bias=0, confidence=0.8, click=True):
    while True:
        img = pag.locateOnScreen(path, confidence=confidence)
        if path_s != '':
            img_s = pag.locateOnScreen(path_s, confidence=0.8)
        else:
            img_s = None
        if img_s is not None:
            print('already done')
            break
        if img is not None:
            print('image finded')
            x, y = pag.center(img)
            if click:
                pag.leftClick(x + x_bias, y + y_bias)
                break
            else:
                pag.moveTo(x + x_bias, y + y_bias)
                break
        else:
            print('failed')


# 基本物理量的单位
def get_exp(dw_expr):
    # 基本物理量的单位
    pm, nm, um, mm, cm, dm, m = symbols('pm, nm, um, mm, cm, dm, m')
    ps, ns, us, ms, s = symbols('ps, ns, us, ms, s')
    pg, ng, ug, mg, g, kg = symbols('pg, ng, ug, mg, g, kg')
    pA, nA, uA, mA, A = symbols('pA, nA, uA, mA, A')
    pV, nV, uV, mV, V = symbols('pV, nV, uV, mV, V')
    K = symbols('K')
    mmol, mol = symbols('mmol, mol')
    cd = symbols('cd')
    Hz = symbols('Hz')
    mJ, J, kJ = symbols('mJ, J, kJ')
    pW, nW, uW, mW, W, kW = symbols('pW, nW ,uW, mW, W, kW')
    uPa, mPa, Pa, kPa, MPa, GPa = symbols('uPa, mPa, Pa, kPa, MPa, GPa')

    dw_dict = [
        (pm, 1e-12), (nm, 1e-9), (um, 1e-6), (mm, 1e-3), (cm, 1e-2), (dm, 0.1), (m, 1),
        (ps, 1e-12), (ns, 1e-9), (us, 1e-6), (ms, 1e-3), (s, 1),
        (pg, 1e-12), (ng, 1e-9), (ug, 1e-6), (mg, 1e-3), (g, 1e-3), (kg, 1),
        (pA, 1e-12), (nA, 1e-9), (uA, 1e-6), (mA, 1e-3), (A, 1),
        (pV, 1e-12), (nV, 1e-9), (uV, 1e-6), (mV, 1e-3), (V, 1),
        (K, 1), (mmol, 1e-3), (mol, 1), (cd, 1), (Hz, 1),
        (mJ, 1e-3), (J, 1), (kJ, 1e3),
        (pW, 1e-12), (nW, 1e-9), (uW, 1e-6), (mW, 1e-3), (W, 1), (kW, 1e3),
        (uPa, 1e-6), (mPa, 1e-3), (Pa, 1), (kPa, 1e3), (MPa, 1e6), (GPa, 1e9)
    ]

    return sympify(dw_expr).subs(dw_dict)


data_storage = []
dw_storage = []
angle_storage = []
base_exp = 1.0

print('这个程序会生成(或在现存的docx文档后添加)一个docx格式的文档, 包含了大物实验的数据处理和误差分析部分')
path = input('输入word的文件名(可以不存在, 会新建的), 并且包含它的路径(比如D:/Experiments/切变模量):')
if 'docx' not in path:
    path = path + '.docx'

print(path)
P = input("输入实验的置信系数0.68(default),0.90,0.95   (选择1,2,3也行):")
if P == '':
    P = '0.68'
if P == '1':
    P = '0.68'
if P == '2':
    P = '0.90'
if P == '3':
    P = '0.95'
Greek_list = ['alpha', 'delta', 'epsilon',
              'varepsilon', 'eta',
              'theta', 'vartheta', 'kappa', 'lambda',
              'mu', 'nu', 'xi', 'omicron', 'rho', 'sigma',
              'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega', 'varphi']
print('警告--------警告---------警告')
print('数据太大， 自求多福')
print('变量符号  不能是 C , O,  Q, N, I, E, S, beta, gamma, zeta, pi')
print('变量符号  不能是 C , O,  Q, N, I, E, S, beta, gamma, zeta, pi')
print('变量符号  不能是 C , O,  Q, N, I, E, S, beta, gamma, zeta, pi')
forbiden_list = ['C', 'O', 'Q', 'N', 'I', 'E', 'S', 'beta', 'gamma', 'zeta', 'pi']
# time.sleep(3)
print('实在要用必须加上下标')

while True:
    name = input('输入测量量名称, 若不需要输入done:')

    if name == 'done':
        break
    remake_name = 're'
    i = 0
    while remake_name == 're':
        if i == 0:
            remake_name = input('输入测量量符号(可用希腊字母)(用来计算的核心部分, 千万别错了):')
        else:
            name = input('输入测量量名称, 若不需要输入done:')
            if name == 'done':
                break
            remake_name = input('输入测量量符号(可用希腊字母)(用来计算的核心部分, 千万别错了):')
        i += 1
    i = 0
    if name == 'done':
        break

    figure = remake_name
    if figure in forbiden_list:
        print('不合法的变量名, 更换名字或者添加下标')
        continue
    Gf = False
    for item in Greek_list:
        if item in figure:
            Gf = True
            break
    print('Greek_figure:', Gf)

    remake_figure = 're'
    while remake_figure == 're':
        if i == 0:
            remake_figure = input('输入数据:')
        else:
            figure = input('输入测量量符号(可用希腊字母)(用来计算的核心部分, 千万别错了):')
            if figure in forbiden_list:
                print('不合法变量')
                continue
            Gf = False
            for item in Greek_list:
                if item in figure:
                    Gf = True
                    break
            print('Greek_figure:', Gf)
            remake_figure = input('输入数据:')
        i += 1

    if Gf:
        gf = '\\'
    else:
        gf = ''
    remake_data = 're'

    data_list = remake_figure
    i = 0
    while remake_data == 're':
        if i == 0:
            remake_data = input('输入测量量单位, 不要打括号:')
        else:
            data_list = input('输入数据:')
            remake_data = input('输入测量量单位, 不要打括号:')
        i += 1
    data_list = data_list.split()
    var_is_angle = False
    if ',' in data_list[0]:
        var_is_angle = True
        for i in range(len(data_list)):
            # print(item)
            data_list[i] = angle2float(data_list[i])
            # print(item)
    print(data_list)
    len_data = len(data_list)
    if len_data == 2:
        print('故意找茬是吧')
        continue
    if len_data >= 3:
        enough_data = True
    else:
        enough_data = False

    remake_dw = 're'
    dw = remake_data
    i = 0
    while remake_dw == 're':
        if i == 0:
            remake_dw = input('输入分布类型   正态(default),均匀,三角   (选择1,2,3): ')
        else:
            dw = input('输入测量量单位, 不要打括号:')
            remake_dw = input('输入分布类型   正态(default),均匀,三角   (选择1,2,3): ')
        i += 1
    if dw:
        var_exp = get_exp(dw)
    else:
        var_exp = 1.0

    print('这个变量的单位的次方是国际制的', var_exp, '倍')

    if not enough_data:

        print('distribute type automatically set to triangular')
        distribute_type = 3
        remake_distribute = input('输入仪器允差:')
    else:
        remake_distribute = 're'
        distribute_type = remake_dw
        i = 0
        while remake_distribute == 're':
            if i == 0:
                remake_distribute = input('输入仪器允差:')
            else:
                distribute_type = input('输入分布类型   正态,均匀,三角   (选择1,2,3): ')
                remake_distribute = input('输入仪器允差:')
        i += 1
        if distribute_type == '':
            distribute_type = 1
    distribute_type = int(distribute_type)

    remake_delta = 're'
    if ',' in remake_distribute:
        remake_distribute = angle2float(remake_distribute)
    while remake_distribute == '':
        remake_distribute = input('允差不能为空，输入允差:')
    delta = float(remake_distribute)
    i = 0
    # delta = float(input('输入仪器允差:'))
    # print('下方粘贴数据(手动输入以空格分割), 回车(不支持多行输入):')
    while remake_delta == 're':
        if i == 0:
            remake_delta = input('re?不re敲回车')
        else:
            delta = float(input('输入仪器允差:'))
            remake_delta = input('re?不re敲回车')
        i += 1
    eff_len = get_eff_len(data_list[0])
    for i in range(len_data):
        data_list[i] = float(data_list[i])

    if enough_data:
        u_a = np.std(data_list) / np.sqrt(len_data - 1)
    else:
        u_a = 0.0

    T_A = {
        '1': [-1, 0, -1, 1.32, 1.2, 1.14, 1.11, 1.09, 1.08, 1.07, 1.06],
        '2': [-1, -1, -1, 2.92, 2.35, 2.13, 2.02, 1.94, 1.86, 1.83, 1.76],
        '3': [-1, -1, -1, 4.30, 3.18, 2.78, 2.57, 2.46, 2.37, 2.31, 2.26],
        '0.68': [-1, -1, -1, 1.32, 1.2, 1.14, 1.11, 1.09, 1.08, 1.07, 1.06],
        '0.90': [-1, -1, -1, 2.92, 2.35, 2.13, 2.02, 1.94, 1.86, 1.83, 1.76],
        '0.95': [-1, -1, -1, 4.30, 3.18, 2.78, 2.57, 2.46, 2.37, 2.31, 2.26]
    }

    t_A = T_A[P][len_data]

    K_P = {
        '1': [1.000, 1.183, 1.064],
        '2': [1.650, 1.559, 1.675],
        '3': [1.960, 1.645, 1.901],
        '0.68': [1.000, 1.183, 1.064],
        '0.90': [1.650, 1.559, 1.675],
        '0.95': [1.960, 1.645, 1.901]
    }
    C = [3, np.sqrt(3), np.sqrt(6)]
    c = C[distribute_type - 1]
    C_s = ['3', '\sqrt{3}', '\sqrt{6}']
    k_p = K_P[P][distribute_type - 1]
    ave = np.average(data_list)
    U = np.sqrt(np.square(t_A * u_a) + np.square(k_p * delta / c))
    U_r = eff_num(str(float(U) / np.average(data_list) * 100), 2)

    first = er_fendu(U)[0]
    if first == '1' or first == '2':
        U = eff_num(str(U), 2)
    else:
        U = eff_num(str(U), 1)

    first = er_fendu(U)[0]
    if first == '1' or first == '2':
        U = eff_num(str(U), 2)
    else:
        U = eff_num(str(U), 1)
    U = str(eval(U.replace("^", '**')))

    #     为啥这个东西要跑两遍呢？因为可能遇到0.295保留两位之后U变成0.30，这样就不对了
    ave = str(ave)
    print(ave)
    if enough_data:
        std = np.std(data_list) * np.sqrt(len_data) / np.sqrt(len_data - 1)
    else:
        std = 0

    print('avefendu', er_fendu(ave, error=0))
    print('Ufendu', er_fendu(U, error=1))
    if er_fendu(ave, error=0)[1] <= er_fendu(U)[1]:
        print('故意找茬是吧, 误差这么大')
        continue
    print(ave)
    print(er_fendu(ave, error=0))
    print(U)
    print(er_fendu(U))
    ave_show = eff_num(ave,
                       max(abs(er_fendu(ave, error=0)[1] - er_fendu(U)[1]) + 1, get_eff_len(str(data_list[0])) + 1))
    ave = eff_num(ave, abs(er_fendu(ave, error=0)[1] - er_fendu(U)[1]) + 1)
    print('strave=', ave, 'fenduave=', er_fendu(ave, error=0), 'fenduU=', er_fendu(U))
    if std:
        std = eff_num(str(std), 2)
    else:
        std = zero_deci(deci_len(ave))
    if u_a:
        first = er_fendu(u_a)[0]
        if first == '1' or first == '2':
            u_a = eff_num(str(u_a), 2)
        else:
            u_a = eff_num(str(u_a), 1)
    else:
        u_a = zero_deci(deci_len(ave))

    print('ave=', ave)
    print('std=', std)
    if enough_data:
        print('u_a=', u_a)

    print('C=', C_s[distribute_type - 1])
    if enough_data:
        print('t_A=', t_A)
    print('k_p=', k_p)
    print('U_测=', U)
    print('U_r=', U_r + '%')
    #     现在进行变量处理
    u_figure = 'U_' + figure

    trans = ''
    if var_is_angle:
        trans = input('转换为弧度制(default), 输入N取消 (角度制只能加减):')

    if var_is_angle and not trans == 'N':
        ave_1 = float(ave) * 3.1415926 / 180
        U_1 = float(U) * 3.1415926 / 180
    else:
        ave_1 = eval(ave.replace('^', '**'))
        U_1 = eval(U.replace('^', '**'))
    globals()[figure] = symbols(figure)
    globals()[u_figure] = symbols(u_figure)

    if not var_is_angle:
        data_storage.append(((globals()[figure], eval(ave.replace('^', '**')) * var_exp),
                             (globals()[u_figure], eval(U.replace('^', '**')) * var_exp)))
    else:
        data_storage.append(
            ((globals()[figure], eval(ave.replace('^', '**'))), (globals()[u_figure], eval(U.replace('^', '**')))))

    if var_is_angle:
        for i in range(len_data):
            data_list[i] = float2angle(data_list[i])

        ave_show = float2angle(ave)

        ave = float2angle(ave)
        if enough_data:
            u_a = float2angle(u_a)
        std = float2angle(std)
        U = float2angle(U)
    if not var_is_angle:
        U = sci2str(U)
    try:
        doc = docx.Document(path)
    except Exception:
        doc = docx.Document()
    doc.styles['Normal'].font.name = u'宋体'
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    doc.styles['Normal'].font.size = Pt(10.5)
    doc.styles['Normal'].font.color.rgb = RGBColor(0, 0, 0)

    para_3 = doc.add_paragraph('')

    if enough_data:
        if dw:
            header = doc.add_paragraph(name + '{\quad}' + gf + figure + '(' + dw + ')' + ':')
        else:
            header = doc.add_paragraph(name + '{\quad}' + gf + figure + ':')

    else:
        if dw:
            header = doc.add_paragraph(
                name + '{\quad}' + gf + figure + '(' + dw + ')' + ':' + '{\qquad}' + str(data_list[0]))
        else:
            header = doc.add_paragraph(name + '{\quad}' + gf + figure + ':' + '{\qquad}' + str(data_list[0]))

    if enough_data:
        try:
            table = doc.add_table(rows=2, cols=len_data + 1, style='Table Grid')
        except Exception:
            table = doc.add_table(rows=2, cols=len_data + 1, style='Normal Table')

        line1 = table.rows[0].cells
        line1[0].text = '组数'
        for i in range(1, len_data + 1):
            line1[i].text = str(i)
        line2 = table.rows[1].cells
        line2[0].add_paragraph('读数 ')
        for i in range(1, len_data + 1):
            line2[i].add_paragraph(str(data_list[i - 1]))
    if enough_data:
        para_1 = doc.add_paragraph('')
    para0 = doc.add_paragraph('P=' + str(P))
    if dw:
        para1 = doc.add_paragraph('\\bar' + '{' + gf + figure + '}' + '=' + str(ave_show) + '' + dw)
        para2 = doc.add_paragraph('\\sigma_' + '{' + gf + figure + '}' + '=' + str(std) + ' ' + dw)
    else:
        para1 = doc.add_paragraph('\\bar' + '{' + gf + figure + '}' + '=' + str(ave_show))
        para2 = doc.add_paragraph('\\sigma_' + '{' + gf + figure + '}' + '=' + str(std))
    if enough_data:
        para5 = doc.add_paragraph('u_A =' + str(u_a) + ' ' + dw + '{\qquad}' + 't_A=' + str(t_A))
    para4 = doc.add_paragraph('C=' + C_s[distribute_type - 1] + '{\qquad}' + 'k_p' + '=' + str(k_p))

    para7 = doc.add_paragraph(
        'U_' + '{' + gf + figure + '}' + '=' + str(U) + ' ' + dw + '{\qquad}' + 'U_r=' + str(U_r) + '%')
    if dw:
        para9 = doc.add_paragraph(gf + figure + '=' + '(' + ave + '\\pm ' + U + ')' + ' ' + dw)
    else:
        para9 = doc.add_paragraph(gf + figure + '=' + ave + '\\pm ' + U)
    try:
        doc.save(path)
    except Exception:
        a = input('your file is open, close it and input y or Y to continue:')
        if a == 'y' or a == 'Y':
            doc.save(path)
    print(name + '      录入成功')

print(data_storage)

var_all = []
for i in range(len(data_storage)):
    var_all.extend(data_storage[i])

# 合成处理
while True:

    print('涉及角度的量, 只要不是加减法, 都要使用弧度制')
    name = input('物理量(final)名称, 输入done退出:')

    if name == 'done':
        break
    remake_name = 're'
    i = 0
    while remake_name == 're':
        if i == 0:
            remake_name = input('输入物理量符号:')
        else:
            name = input('物理量(final)名称, 输入done退出:')
            if name == 'done':
                break
            remake_name = input('输入物理量符号:')
        i += 1
    if name == 'done':
        break

    figure = remake_name

    remake_figure = 're'

    i = 0
    while remake_figure == 're':
        if i == 0:
            remake_figure = input('输入单位:')
        else:
            figure = input('输入物理量符号:')
            remake_figure = input('输入单位:')
        i += 1

    Gf = False
    for item in Greek_list:
        if item in figure:
            Gf = True
            break
    print('Greek_figure:', Gf)
    if Gf:
        gf = '\\'
    else:
        gf = ''

    dw = remake_figure
    remake_dw = 're'
    i = 0
    if dw:
        answer_exp = get_exp(dw)
        amend_exp = answer_exp
    else:
        amend_exp = 1.0

    while remake_dw == 're':
        if i == 0:
            remake_dw = input('输入物理量的表达式的等号右边(支持^表示次方):')
        else:
            dw = input('输入单位:')
            remake_dw = input('输入物理量的表达式的等号右边(支持^表示次方):')
        i += 1

    str_expr = remake_dw
    remake_str = 're'
    i = 0
    while remake_str == 're':
        if i == 0:
            remake_str = input('re?不re敲回车')
        else:
            str_expr = input('输入物理量的表达式(支持^表示次方, 还有不要少打括号!!!):')
            remake_str = input('re?不re敲回车')
        i += 1

    str_expr = str_expr.replace('^', '**')
    str_expr = str_expr.replace('（', '(')
    str_expr = str_expr.replace('）', ')')
    print(var_all)
    try:
        expr = sympify(str_expr, rational=True, evaluate=False)

    except Exception:
        print('你这些物理量符号保对吗?')
        print(Exception)
        continue
    print('amend=', amend_exp)
    try:
        ave = abs(float(expr.subs(var_all)) / amend_exp)
    except Exception:
        print(Exception)
        print('检查下公式？')
        continue
    print('这个单位下, ave= ', ave)
    # 输出公式的LaTeX公式
    latex_expr = latex(expr, ln_notation=True)
    # print(latex_expr)
    expr1 = log(expr)
    expr2 = 0
    sig_var = []

    for item in data_storage:

        expr2 = expr2 + (diff(expr1, item[0][0]) * item[1][0]) ** 2
        Gf_1 = False
        for elem in Greek_list:
            if elem in str(item[0][0]):
                Gf_1 = True
                break
        print('var is Greek_figure:', Gf_1)
        if Gf_1:
            gf_1 = '\\'
        else:
            gf_1 = ''

        expr3 = diff(expr1, item[0][0])
        if str(expr3)[0] == '-':
            expr3 = -1 * expr3
        if str(expr3)[0] != '0':
            expr3 = simplify(expr3)
            expr3 = expand(expr3)
            expr3 = factor(expr3)

            sig_var.append(
                '(' + latex(expr3) + 'U_{' + gf_1 + str(item[0][0]) + '})^{2}')

    expr2 = sqrt(expr2)
    print(expr2)
    latex_u_in = '+'.join(sig_var)
    latex_u_in = '\\sqrt' + '{' + latex_u_in + '}'
    print(latex_u_in)

    U_r = float(expr2.subs(var_all).evalf())
    print('U_r=', U_r)
    U = ave * U_r
    U = pure_sci2str(U)
    # 因为U已经乘过amend_exp了, 所以不用再乘

    U_r = eff_num(100 * U_r, 2) + '%'
    first = er_fendu(U)[0]
    print('total U=', U)
    U = pure_sci2str(U)

    ave = pure_sci2str(ave)
    print('strave=', ave)
    print('有效位数=', er_fendu(ave, error=0)[1], er_fendu(U)[1])

    ave = eff_num(ave, abs(er_fendu(ave, error=0)[1] - er_fendu(U)[1]) + 1)

    U = sci2str(U)
    U = sci2str(U)
    print('strU=', U)

    doc = docx.Document(path)

    doc.add_paragraph('')
    doc.add_paragraph('')
    if dw:
        Para_1 = doc.add_paragraph(name + '{\quad}' + gf + figure + '(' + dw + '):')
        Para_0 = doc.add_paragraph('P=' + str(P))
        Para_2 = doc.add_paragraph(gf + figure + '=' + latex_expr + '=' + ave + '(' + dw + ')')
    else:
        Para_1 = doc.add_paragraph(name + '{\quad}' + gf + figure + ':')
        Para_0 = doc.add_paragraph('P=' + str(P))
        Para_2 = doc.add_paragraph(gf + figure + '=' + latex_expr + '=' + ave)
    Para_3 = doc.add_paragraph(
        'U_r =' + '\\frac{U_{' + gf + figure + '}}{' + gf + figure + '}=' + latex_u_in + '=' + U_r)
    if dw:
        Para_4 = doc.add_paragraph('U =' + gf + figure + '\\times' + ' ' + 'U_r=' + U + '(' + dw + ')')
        Para_5 = doc.add_paragraph(gf + figure + '=(' + ave + '\\pm' + U + ')' + dw)
    else:
        Para_4 = doc.add_paragraph('U =' + gf + figure + '\\times' + ' ' + 'U_r=' + U)
        Para_5 = doc.add_paragraph(gf + figure + '=(' + ave + '\\pm' + U + ')')
    try:
        doc.save(path)
    except Exception:
        a = input('your file is open, input y to continue')
        if a == 'y':
            doc.save(path)
    print(name + '  ' + '处理完成')

"""
最后的文件处理
"""

os.startfile(path)
# 不能在下载盘里调用这个， 好像是权限问题， 移动到其它盘就行了
operate("./user.jpg", click=False)
# 判断文件已经打开
pag.moveRel(0, 500)
time.sleep(3)

pag.hotkey('ctrl', 'end')
time.sleep(0.3)

pag.hotkey('ctrl', 'shiftright', 'shiftleft', 'home')

time.sleep(1)
pag.hotkey('alt', '=')
time.sleep(0.1)
pag.hotkey('alt', 'shift', 'p')
time.sleep(0.1)
pag.hotkey('ctrl', 'l')
time.sleep(1)
pag.hotkey('ctrl', 's')

print('finished')

# 希望各位能赞助作者抽宵宫
>>>>>>> e84f0de43632325efd05078ad786930a9bca81db:DataProcesserApi.py
